package yto.freemarker.springcloud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import yto.freemarker.springcloud.entity.User;

/**
 * @author dongxing
 * @create 2017-12-24 17:00
 **/
@RestController
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/simple/{id}")
    public User findById(@PathVariable Long id) {
        //http://localhost:8088/simple/
        //vip:virtual ip
        // HAProxy Heartbeat
        ServiceInstance choose = loadBalancerClient.choose("service-provider-movie");
        System.out.println(choose.getHost() + "---" + choose.getPort());
        return restTemplate.getForObject("http://service-provider-movie/simple/" + id, User.class);
    }

    @GetMapping("/test")
    public String test() {
        //指定哪个微服务
        ServiceInstance serviceInstance = loadBalancerClient.choose("service-provider-movie");
        System.out.println("1111" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + ":" + serviceInstance.getServiceId());

        ServiceInstance serviceInstance2 = loadBalancerClient.choose("service-provider-movie");
        System.out.println("222" + serviceInstance2.getHost() + ":" + serviceInstance2.getPort() + ":" + serviceInstance2.getServiceId());
        return "1";
    }
}
